// pages/merchant/news-management/index.js
const { FormUtils } = require('../../../utils/form-config.js');
const apiService = require('../../../utils/api.js');

Page({
  data: {
    news: [],
    filteredNews: [],
    searchKeyword: '',
    currentFilter: 'all',
    showModal: false,
    showDeleteModal: false,
    isEdit: false,
    formData: {},
    isFormValid: false,
    selectedNews: null,
    newsStats: {
      total: 0,
      published: 0,
      draft: 0,
      pinned: 0
    }
  },

  onLoad() {
    this.loadNews();
  },

  onShow() {
    this.loadNews();
  },

  // 加载新闻列表
  async loadNews() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 模拟数据，实际应该调用API
      const mockNews = [
        {
          NEWS_ID: 'news_001',
          NEWS_TITLE: '超级泡泡宠物服务升级公告',
          NEWS_DESC: '为了更好地服务广大宠物主人，我们决定对服务进行全面升级...',
          NEWS_CONTENT: '为了更好地服务广大宠物主人，我们决定对服务进行全面升级。新增了多项便民服务，包括在线预约、实时监控、专业护理等。',
          NEWS_CATE_NAME: '公告',
          NEWS_ORDER: 1,
          NEWS_HOME: 1,
          NEWS_STATUS: 1,
          NEWS_VIEW_CNT: 1250,
          createTime: 1640995200000,
          createTimeText: '2025-01-25 10:30'
        },
        {
          NEWS_ID: 'news_002',
          NEWS_TITLE: '春节假期服务时间调整',
          NEWS_DESC: '春节期间我们的服务时间将有所调整，请各位宠物主人注意...',
          NEWS_CONTENT: '春节期间我们的服务时间将有所调整，请各位宠物主人注意。具体时间安排如下：除夕至初六营业时间调整为9:00-18:00。',
          NEWS_CATE_NAME: '活动',
          NEWS_ORDER: 2,
          NEWS_HOME: 0,
          NEWS_STATUS: 1,
          NEWS_VIEW_CNT: 890,
          createTime: 1640995200000,
          createTimeText: '2025-01-24 15:20'
        },
        {
          NEWS_ID: 'news_003',
          NEWS_TITLE: '宠物护理小贴士',
          NEWS_DESC: '分享一些宠物日常护理的小贴士，帮助宠物主人更好地照顾宠物...',
          NEWS_CONTENT: '分享一些宠物日常护理的小贴士，帮助宠物主人更好地照顾宠物。包括饮食、运动、清洁等方面的建议。',
          NEWS_CATE_NAME: '服务',
          NEWS_ORDER: 3,
          NEWS_HOME: 0,
          NEWS_STATUS: 0,
          NEWS_VIEW_CNT: 0,
          createTime: 1640995200000,
          createTimeText: '2025-01-23 09:15'
        },
        {
          NEWS_ID: 'news_004',
          NEWS_TITLE: '新店开业优惠活动',
          NEWS_DESC: '我们的新店即将开业，开业期间有超多优惠活动等着您...',
          NEWS_CONTENT: '我们的新店即将开业，开业期间有超多优惠活动等着您。前100名客户享受5折优惠，还有精美礼品相送。',
          NEWS_CATE_NAME: '活动',
          NEWS_ORDER: 4,
          NEWS_HOME: 0,
          NEWS_STATUS: 1,
          NEWS_VIEW_CNT: 567,
          createTime: 1640995200000,
          createTimeText: '2025-01-22 14:45'
        }
      ];

      // 计算统计数据
      const stats = {
        total: mockNews.length,
        published: mockNews.filter(n => n.NEWS_STATUS === 1).length,
        draft: mockNews.filter(n => n.NEWS_STATUS === 0).length,
        pinned: mockNews.filter(n => n.NEWS_HOME === 1).length
      };

      this.setData({
        news: mockNews,
        filteredNews: mockNews,
        newsStats: stats
      });

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      console.error('加载新闻失败:', error);
    }
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.filterNews(keyword);
  },

  // 筛选条件变化
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.filterNews();
  },

  // 过滤新闻
  filterNews(keyword = '') {
    const { news, currentFilter, searchKeyword } = this.data;
    const searchKey = keyword || searchKeyword;
    let filtered = news;

    // 按状态筛选
    if (currentFilter !== 'all') {
      if (currentFilter === 'published') {
        filtered = filtered.filter(news => news.NEWS_STATUS === 1);
      } else if (currentFilter === 'draft') {
        filtered = filtered.filter(news => news.NEWS_STATUS === 0);
      } else if (currentFilter === 'pinned') {
        filtered = filtered.filter(news => news.NEWS_HOME === 1);
      }
    }

    // 按关键词搜索
    if (searchKey) {
      filtered = filtered.filter(news => 
        news.NEWS_TITLE.toLowerCase().includes(searchKey.toLowerCase()) ||
        news.NEWS_DESC.toLowerCase().includes(searchKey.toLowerCase()) ||
        news.NEWS_CATE_NAME.toLowerCase().includes(searchKey.toLowerCase())
      );
    }

    this.setData({ filteredNews: filtered });
  },

  // 添加新闻
  onAddNews() {
    const formData = FormUtils.initFormData('news');
    this.setData({
      showModal: true,
      isEdit: false,
      formData,
      isFormValid: false
    });
  },

  // 编辑新闻
  onEditNews(e) {
    const item = e.currentTarget.dataset.item;
    const formData = { ...item };
    
    this.setData({
      showModal: true,
      isEdit: true,
      formData,
      selectedNews: item,
      isFormValid: true
    });
  },

  // 切换发布状态
  async onTogglePublishStatus(e) {
    const item = e.currentTarget.dataset.item;
    const newStatus = item.NEWS_STATUS === 1 ? 0 : 1;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { news } = this.data;
      const updatedNews = news.map(n => 
        n.NEWS_ID === item.NEWS_ID ? { ...n, NEWS_STATUS: newStatus } : n
      );
      
      // 重新计算统计数据
      const stats = {
        total: updatedNews.length,
        published: updatedNews.filter(n => n.NEWS_STATUS === 1).length,
        draft: updatedNews.filter(n => n.NEWS_STATUS === 0).length,
        pinned: updatedNews.filter(n => n.NEWS_HOME === 1).length
      };
      
      this.setData({ 
        news: updatedNews,
        newsStats: stats
      });
      this.filterNews();
      
      wx.hideLoading();
      wx.showToast({
        title: newStatus === 1 ? '已发布' : '已下架',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
      console.error('切换发布状态失败:', error);
    }
  },

  // 切换置顶状态
  async onTogglePinStatus(e) {
    const item = e.currentTarget.dataset.item;
    const newPinStatus = item.NEWS_HOME === 1 ? 0 : 1;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { news } = this.data;
      const updatedNews = news.map(n => 
        n.NEWS_ID === item.NEWS_ID ? { ...n, NEWS_HOME: newPinStatus } : n
      );
      
      // 重新计算统计数据
      const stats = {
        total: updatedNews.length,
        published: updatedNews.filter(n => n.NEWS_STATUS === 1).length,
        draft: updatedNews.filter(n => n.NEWS_STATUS === 0).length,
        pinned: updatedNews.filter(n => n.NEWS_HOME === 1).length
      };
      
      this.setData({ 
        news: updatedNews,
        newsStats: stats
      });
      this.filterNews();
      
      wx.hideLoading();
      wx.showToast({
        title: newPinStatus === 1 ? '已置顶' : '已取消置顶',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
      console.error('切换置顶状态失败:', error);
    }
  },

  // 删除新闻
  onDeleteNews(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showDeleteModal: true,
      selectedNews: item
    });
  },

  // 确认删除
  async onConfirmDelete() {
    const { selectedNews } = this.data;
    
    try {
      wx.showLoading({ title: '删除中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { news } = this.data;
      const updatedNews = news.filter(n => n.NEWS_ID !== selectedNews.NEWS_ID);
      
      // 重新计算统计数据
      const stats = {
        total: updatedNews.length,
        published: updatedNews.filter(n => n.NEWS_STATUS === 1).length,
        draft: updatedNews.filter(n => n.NEWS_STATUS === 0).length,
        pinned: updatedNews.filter(n => n.NEWS_HOME === 1).length
      };
      
      this.setData({ 
        news: updatedNews,
        newsStats: stats
      });
      this.filterNews();
      
      wx.hideLoading();
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
      this.onCloseDeleteModal();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      });
      console.error('删除失败:', error);
    }
  },

  // 表单数据变化
  onFormChange(e) {
    const { formData } = e.detail;
    this.setData({ formData });
  },

  // 表单验证
  onFormValidate(e) {
    const { isValid } = e.detail;
    this.setData({ isFormValid: isValid });
  },

  // 确认保存
  async onConfirmSave() {
    if (!this.data.isFormValid) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'error'
      });
      return;
    }

    try {
      wx.showLoading({ title: '保存中...' });
      
      const { formData, isEdit, selectedNews } = this.data;
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新本地数据
      const { news } = this.data;
      let updatedNews;
      
      if (isEdit) {
        // 编辑模式
        updatedNews = news.map(n => 
          n.NEWS_ID === selectedNews.NEWS_ID ? { ...n, ...formData } : n
        );
      } else {
        // 添加模式
        const newNews = {
          ...formData,
          NEWS_ID: 'news_' + Date.now(),
          NEWS_VIEW_CNT: 0,
          createTime: Date.now(),
          createTimeText: new Date().toLocaleString()
        };
        updatedNews = [...news, newNews];
      }
      
      // 重新计算统计数据
      const stats = {
        total: updatedNews.length,
        published: updatedNews.filter(n => n.NEWS_STATUS === 1).length,
        draft: updatedNews.filter(n => n.NEWS_STATUS === 0).length,
        pinned: updatedNews.filter(n => n.NEWS_HOME === 1).length
      };
      
      this.setData({ 
        news: updatedNews,
        newsStats: stats
      });
      this.filterNews();
      
      wx.hideLoading();
      wx.showToast({
        title: isEdit ? '编辑成功' : '发布成功',
        icon: 'success'
      });
      
      this.onCloseModal();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        icon: 'error'
      });
      console.error('保存失败:', error);
    }
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showModal: false,
      formData: {},
      isFormValid: false,
      selectedNews: null
    });
  },

  // 关闭删除确认弹窗
  onCloseDeleteModal() {
    this.setData({
      showDeleteModal: false,
      selectedNews: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  }
});
